package koalacam.local;

import java.io.File;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

/**
 * 1:1 认证
 * @author Wangshutao
 * 2016年7月5日
 */
public class Checkin {
	
	/**
	 * 1:1 认证
	 * @param url
	 * @param photo 用于认证的照片
	 * @param person_id 认证者的ID（前端登录用户的id）
	 * @throws Exception
	 */
	public static void checkin(String url,String photo,Integer person_id) throws Exception{
		System.out.println("Start POST /checkin 1:1 认证 ...");
		
		//创建默认HttpClient
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost request = new HttpPost(url);
        
        //设置用于认证的照片 和 认证者的ID
        MultipartEntity reqEntity = new MultipartEntity();  
        reqEntity.addPart("image", new FileBody(new File(photo)));
        reqEntity.addPart("person_id", new StringBody(person_id.toString()));
        request.setEntity(reqEntity);

        CloseableHttpResponse response = httpclient.execute(request);
        String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(responseBody);

        //解析JSON 
        JSONObject resp = new JSONObject(responseBody);
        int result = resp.optInt("code", -1);
        if (result != 0) {
            System.err.println("code:" + result);
        }else{
        	
        	//依据返回的用户id 与 person_id 比较 判断认证是否成功
        	int return_person_id = resp.getJSONObject("data").getInt("person_id");
        	if(return_person_id == person_id){
        		System.out.println("认证通过");
        	}else{
        		System.out.println("认证失败");	
        	}
        }
	}
	

}
